<?php

/**
 * Video Url Parser
 */
class VideoUrl
{
    // YOUTUBE URL PATERN SRC : http://linuxpanda.wordpress.com/2013/07/24/ultimate-best-regex-pattern-to-get-grab-parse-youtube-video-id-from-any-youtube-link-url/
    // VIMEO URL PATERN SRC : http://stackoverflow.com/questions/10488943/easy-way-to-get-vimeo-id-from-a-vimeo-url

    const TYPE_YOUTUBE = 'youtube';
    const YOUTUBE_PATERN_URL = "~(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[a-z0-9;:@?&%=+\/\$_.-]*~i";
    const YOUTUBE_PATERN_URL_MATCH_INDEX = 1;
    const TYPE_VIMEO = 'vimeo';
    const VIMEO_PATERN_URL = "#(https?://)?(www.)?(player.)?vimeo.com/([a-z]*/)*([0-9]{6,11})[?]?.*#i";
    const VIMEO_PATERN_URL_MATCH_INDEX = 5;

    /**
     * @param string The original video url
     * @param string The video type passed and returned by reference
     * @return string The embed url to use in the iframe src
     */
    public static function getEmbedUrl($url, &$type = null)
    {
        $videoID = self::getVideoId($url, $type);

        if ($type === self::TYPE_YOUTUBE) {
            return "http://www.youtube.com/embed/" . $videoID;
        }
        if ($type === self::TYPE_VIMEO) {
            return 'http://player.vimeo.com/video/' . $videoID;
        }

        return $url;
    }

    /**
     * @param string The original video url
     * @param string The video type passed and returned by reference
     * @return string The video ID
     */
    public static function getVideoId($url, &$type = null)
    {
        // YOUTUBE
        if ($type === self::TYPE_YOUTUBE || (!$type && preg_match(self::YOUTUBE_PATERN_URL, $url, $matches))) {
            $type = self::TYPE_YOUTUBE;
            return $matches[self::YOUTUBE_PATERN_URL_MATCH_INDEX];
        }

        // VIMEO
        if ($type === self::TYPE_VIMEO || (!$type && preg_match(self::VIMEO_PATERN_URL, $url, $matches))) {
            $type = self::TYPE_VIMEO;
            return $matches[self::VIMEO_PATERN_URL_MATCH_INDEX];
        }

        return $url;
    }

}
